<?php
/**
 * @info 网页授权model类
 * @author Jackie Yang
 * @date 20140506
 */
class model_oauth extends model_base{
	
    /**
     * @info 网页授权第一步  拼接url进行授权
     * @author Jackie Yang
     * @date 20140506
     * @param $back 授权后返回的url地址  如：host+/?act=weixin&st=return_url
     *        返回url方法中接收$_GET['code']作为参数调用第二步网页授权
     */
	public static function authorize($back=''){
	   	if(empty($back)){
	   	    framework_static_function::write_log('oauth2.0 backurl is empty!','weixin_oauth');
	   	    exit;
	   	}
        $_SESSION['state'] = $state = sha1(self::rand_str(25));
        $back = urlencode($back);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
        $url .= 'appid='.APPID;
        $url .= '&redirect_uri='.$back;
        $url .= '&response_type=code&scope=snsapi_base&state='.$state;
        $url .= '#wechat_redirect';
        framework_static_function::write_log($url,'weixin_oauth');
        header("HTTP/1.1 301 Moved Permanently"); 
        header("Location:$url"); exit;
    }
    
    /**
     * @info 获取随机字符串
     * @author Jackie Yang
     * @param $num  字符串的位数
     */
    public static function rand_str($num=25){
        if($num>50){
            $num = 25;
        }
        $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $res = '';
        for($i=0;$i<$num;$i++){
            $res .= substr($str, rand(0,61),1);
        }
        return $res;
    }
    
    /**
     * @info 网页授权第二步   第一步返回url的方法中调用此方法
     * @author Jackie Yang
     * @date 20140506
     * @param $code 第一步授权返回url方法中接收的code值
     * 返回网页授权微信用户的id号
     */
    public static function second_authorize($code=''){
        if(empty($code)){
            return FALSE;
        }
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        $url .= 'appid='.APPID;
        $url .= '&secret='.APPSECRET;
        $url .= '&code='.$code;
        $url .= '&grant_type=authorization_code';
        $res = model_weixin::http_post($url,'');
        framework_static_function::write_log('second_authorize :'.$res,'weixin_oauth');
        if($res != FALSE){
            $result = json_decode($res,TRUE);
            if(empty($result) || array_key_exists('errcode', $result)){
                framework_static_function::write_log('second_authorize failed:'.$res,'weixin_oauth');
                return FALSE;
            }
            
           /*  $access_token_info['access_token'] = $result['access_token'];
            $access_token_info['expires_in'] = $result['expires_in'];
            file_put_contents(ACCESSTOKEN_FILE, json_encode($access_token_info)); */
            model_user::resgiter($result['openid']);
            return $result['openid']; exit;
        }
        return FALSE;
    }
}